package org.pedia2.apps.demo.helloworld.client;

import java.util.List;

import org.pedia2.apps.demo.helloworld.client.model.City;
import org.pedia2.apps.demo.helloworld.client.model.Taxi;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class HelloWorld implements EntryPoint{

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network " + "connection and try again.";
	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
	//
	private DialogBox dialogBox = new DialogBox();
	private Label textToServerLabel = new Label();
	private HTML serverResponseLabel = new HTML();
	private Button closeButton = new Button("Close");
	//
	private ListBox cityListBox = new ListBox();
	private ListBox taxiListBox = new ListBox();

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		// Create the popup dialog box
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);
		//
		final Button sendButton = new Button("Create City");
		final TextBox nameField = new TextBox();
		nameField.setText("GWT User");
		cityListBox.setVisibleItemCount(5);
		RootPanel.get("cityList").add(cityListBox);
		// Refresh list
		final Button refreshButton = new Button("Refresh");
		RootPanel.get("cityRefresh").add(refreshButton);
		//
		refreshButton.addClickHandler(new ClickHandler(){

			public void onClick(ClickEvent event) {
				refreshCityList();
			}
		});
		// We can add style names to widgets
		sendButton.addStyleName("sendButton");
		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("sendButtonContainer").add(sendButton);
		Button cityInfo = new Button("City Info", new ClickHandler(){

			public void onClick(ClickEvent event) {
				if (cityListBox.getSelectedIndex() > -1) {
					String cityId = cityListBox.getValue(cityListBox.getSelectedIndex());
					greetingService.getCity(cityId, new AsyncCallback<City>(){

						public void onFailure(Throwable caught) {
							dialogBox.setText("Remote Procedure Call - Failure");
							serverResponseLabel.addStyleName("serverResponseLabelError");
							serverResponseLabel.setHTML(SERVER_ERROR);
							dialogBox.center();
							closeButton.setFocus(true);
						}

						public void onSuccess(City result) {
							dialogBox.setText("Remote Procedure Call - Failure");
							serverResponseLabel.removeStyleName("serverResponseLabelError");
							serverResponseLabel.setHTML("City: " + result.getName() + " <br/>EncodedKey: " + result.getEncodedKey()
									+ " <br />EncodedKey.length: " + result.getEncodedKey().length());
							dialogBox.center();
							closeButton.setFocus(true);
						}
					});
				}
			}
		});
		RootPanel.get("sendButtonContainer").add(cityInfo);
		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();
		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler(){

			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});
		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler{

			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendNameToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void sendNameToServer() {
				sendButton.setEnabled(false);
				String textToServer = nameField.getText();
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.createCity(textToServer, new AsyncCallback<City>(){

					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
						dialogBox.setText("Remote Procedure Call - Failure");
						serverResponseLabel.addStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(SERVER_ERROR);
						dialogBox.center();
						closeButton.setFocus(true);
					}

					public void onSuccess(City result) {
						dialogBox.setText("Remote Procedure Call");
						serverResponseLabel.removeStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML("City: " + result.getName() + " EncodedKey: " + result.getEncodedKey()
								+ " <br />EncodedKey.length: " + result.getEncodedKey().length());
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});
			}
		}
		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
		refreshCityList();
		buildTaxiPanel();
	}

	private void buildTaxiPanel() {
		HorizontalPanel hp = new HorizontalPanel();
		VerticalPanel vp = new VerticalPanel();
		VerticalPanel vp1 = new VerticalPanel();
		Label l1 = new Label("Taxi name : ");
		vp1.add(l1);
		final TextBox taxiName = new TextBox();
		vp1.add(taxiName);
		Label l2 = new Label("Phone :");
		vp1.add(l2);
		final TextBox taxiPhone = new TextBox();
		vp1.add(taxiPhone);
		hp.add(vp1);
		VerticalPanel vp2 = new VerticalPanel();
		Button createTaxi = new Button("Create taxi", new ClickHandler(){

			public void onClick(ClickEvent event) {
				String taxiCompanyName = taxiName.getValue();
				String taxiCompanyPhone = taxiPhone.getValue();
				String cityId = cityListBox.getValue(cityListBox.getSelectedIndex());
				greetingService.createTaxi(taxiCompanyName, taxiCompanyPhone, cityId, new AsyncCallback<Taxi>(){

					public void onFailure(Throwable caught) {
						dialogBox.setText("Remote Procedure Call");
						serverResponseLabel.removeStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(caught.getStackTrace().toString());
						dialogBox.center();
						closeButton.setFocus(true);
					}

					public void onSuccess(Taxi result) {
						dialogBox.setText("Remote Procedure Call");
						serverResponseLabel.removeStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML("Taxi: " + result.getName() + " Phone:" + result.getPhone() + " EncodedKey: "
								+ result.getEncodedKey() + " <br />EncodedKey.length: " + result.getEncodedKey().length());
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});
			}
		});
		vp2.add(createTaxi);
		Button getTaxiInfo = new Button("Taxi info", new ClickHandler(){

			public void onClick(ClickEvent event) {
				if (taxiListBox.getSelectedIndex() > -1) {
					String taxiId = taxiListBox.getValue(taxiListBox.getSelectedIndex());
					greetingService.getTaxi(taxiId, new AsyncCallback<Taxi>(){

						public void onFailure(Throwable caught) {
							dialogBox.setText("Remote Procedure Call - Failure");
							serverResponseLabel.addStyleName("serverResponseLabelError");
							serverResponseLabel.setHTML(caught.getStackTrace().toString());
							dialogBox.center();
							closeButton.setFocus(true);
						}

						public void onSuccess(Taxi result) {
							dialogBox.setText("Remote Procedure Call - Failure");
							serverResponseLabel.addStyleName("serverResponseLabelError");
							serverResponseLabel.setHTML("Taxi: " + result.getName() + " <br />Phone:" + result.getPhone()
									+ " <br />EncodedKey: " + result.getEncodedKey() + " <br />EncodedKey.length: "
									+ result.getEncodedKey().length() + " <br /> City.Name" + result.getCity().getName());
							dialogBox.center();
							closeButton.setFocus(true);
						}
					});
				}
			}
		});
		vp2.add(getTaxiInfo);
		Button refreshTaxi = new Button("Refresh Taxi List", new ClickHandler(){

			public void onClick(ClickEvent event) {
				refreshTaxiList();
			}
		});
		vp2.add(refreshTaxi);
		Button getTaxiFromCity = new Button("Taxi for city", new ClickHandler(){

			public void onClick(ClickEvent event) {
				getTaxiForCity();
			}
		});
		vp2.add(getTaxiFromCity);
		Button updateSelectedTaxi = new Button("Update selected taxi", new ClickHandler(){

			public void onClick(ClickEvent event) {
				updateTaxi(taxiName.getValue(), taxiPhone.getValue());
			}
		});
		vp2.add(updateSelectedTaxi);
		Button changeTaxiCity = new Button("Taxi change city", new ClickHandler(){

			public void onClick(ClickEvent event) {
				if (taxiListBox.getSelectedIndex() > -1 && cityListBox.getSelectedIndex() > -1) {
					String taxiId = taxiListBox.getValue(taxiListBox.getSelectedIndex());
					String cityId = cityListBox.getValue(cityListBox.getSelectedIndex());
					greetingService.changeCityOfTaxi(taxiId, cityId, new AsyncCallback<Taxi>(){

						public void onFailure(Throwable caught) {
							dialogBox.setText("Remote Procedure Call - Failure");
							serverResponseLabel.addStyleName("serverResponseLabelError");
							serverResponseLabel.setHTML(caught.getStackTrace().toString());
							dialogBox.center();
							closeButton.setFocus(true);
						}

						public void onSuccess(Taxi result) {
							dialogBox.setText("Remote Procedure Call - Failure");
							serverResponseLabel.addStyleName("serverResponseLabelError");
							serverResponseLabel.setHTML("Taxi: " + result.getName() + " <br />Phone:" + result.getPhone()
									+ " <br />EncodedKey: " + result.getEncodedKey() + " <br /> City.Name" + result.getCity().getName());
							dialogBox.center();
							closeButton.setFocus(true);
						}
					});
				}
			}
		});
		vp2.add(changeTaxiCity);
		hp.add(vp2);
		vp.add(hp);
		vp.add(taxiListBox);
		taxiListBox.setVisibleItemCount(5);
		RootPanel.get("taxiPanel").add(vp);
	}

	protected void updateTaxi(String taxiCompanyName, String taxiCompanyPhone) {
		if (taxiListBox.getSelectedIndex() > -1) {
			String taxiId = taxiListBox.getValue(taxiListBox.getSelectedIndex());
			greetingService.updateTaxi(taxiId, taxiCompanyName, taxiCompanyPhone, new AsyncCallback<Taxi>(){

				public void onFailure(Throwable caught) {
					dialogBox.setText("Remote Procedure Call - Failure");
					serverResponseLabel.addStyleName("serverResponseLabelError");
					serverResponseLabel.setHTML(caught.getMessage());
					dialogBox.center();
					closeButton.setFocus(true);
				}

				public void onSuccess(Taxi result) {
					dialogBox.setText("Remote Procedure Call - Failure");
					serverResponseLabel.addStyleName("serverResponseLabelError");
					serverResponseLabel.setHTML("Taxi: " + result.getName() + " <br />Phone:" + result.getPhone()
							+ " <br />EncodedKey: " + result.getEncodedKey() + " <br /> City.Name" + result.getCity().getName());
					dialogBox.center();
					closeButton.setFocus(true);
				}
			});
		}
	}

	protected void refreshTaxiList() {
		greetingService.getAllTaxiList(new AsyncCallback<List<Taxi>>(){

			public void onFailure(Throwable caught) {
				dialogBox.setText("Remote Procedure Call - Failure");
				serverResponseLabel.addStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(caught.getMessage());
				dialogBox.center();
				closeButton.setFocus(true);
			}

			public void onSuccess(List<Taxi> result) {
				taxiListBox.clear();
				for (Taxi taxi : result)
					taxiListBox.addItem(taxi.getName() + " " + taxi.getPhone(), taxi.getEncodedKey());
			}
		});
	}

	protected void getTaxiForCity() {
		String cityId = cityListBox.getValue(cityListBox.getSelectedIndex());
		greetingService.getTaxiListForCity(cityId, new AsyncCallback<List<Taxi>>(){

			public void onFailure(Throwable caught) {
				dialogBox.setText("Remote Procedure Call - Failure");
				serverResponseLabel.addStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(caught.getMessage());
				dialogBox.center();
				closeButton.setFocus(true);
			}

			public void onSuccess(List<Taxi> result) {
				taxiListBox.clear();
				if (result != null) {
					for (Taxi taxi : result) {
						taxiListBox.addItem(taxi.getName() + " " + taxi.getPhone(), taxi.getEncodedKey());
					}
				} else {
					dialogBox.setText("Remote Procedure Call - Failure");
					serverResponseLabel.addStyleName("serverResponseLabelError");
					serverResponseLabel.setHTML("List is empty !");
					dialogBox.center();
					closeButton.setFocus(true);
				}
			}
		});
	}

	protected void refreshCityList() {
		greetingService.getCityList(new AsyncCallback<List<City>>(){

			public void onFailure(Throwable caught) {
				dialogBox.setText("Remote Procedure Call - Failure");
				serverResponseLabel.addStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(caught.getMessage());
				dialogBox.center();
				closeButton.setFocus(true);
			}

			public void onSuccess(List<City> result) {
				cityListBox.clear();
				if (result != null) {
					for (City city : result) {
						cityListBox.addItem(city.getName(), city.getEncodedKey());
					}
				} else {
					dialogBox.setText("Remote Procedure Call - Failure");
					serverResponseLabel.addStyleName("serverResponseLabelError");
					serverResponseLabel.setHTML("List is empty !");
					dialogBox.center();
					closeButton.setFocus(true);
				}
			}
		});
	}
}
